package com.lemo.hibernate.entity.n21;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class HibernateDemo3 {

	SessionFactory sessionFactory = null;
	Session session = null;
	Transaction transaction = null;

	@Before
	public void init() {
		Configuration configuration = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
				.buildServiceRegistry();
		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();
	}

	@After
	public void destroy() {
		transaction.commit();
		session.close();
		sessionFactory.close();
	}

	@Test
	public void testnTo1Save() {
		
		Customer c1 = new Customer();
		c1.setCustomerName("客户1");
//		Customer c2 = new Customer();
//		c2.setCustomerName("客户2");
		
		Order o1 = new Order();
		o1.setOrderName("订单1");
		o1.setCustomer(c1);
		
		Order o2 = new Order();
		o2.setOrderName("订单2");
		o2.setCustomer(c1);
		
		session.save(c1);
		session.save(o1);
		
	}
	
	@Test
	public void testnTo1Get() {
		Order order =(Order) session.get(Order.class, 1);
		System.out.println(order.getOrderName());
		System.out.println(order.getCustomer().getCustomerName());
	}
}
